<script setup>
import { onMounted, ref } from 'vue'

import { Scene } from "../utils/Sence"

import { SenceGrid } from "../utils/SenceGrid"

const list = ref([
  { 
    id: "canvas01",
    type: "line",
    left: 0,
    top: 0,
    data: [
    { x: 10, y: 100 },
    { x: 50, y: 200 },
    { x: 100, y: 300 },
    { x: 150, y: 20 },
    { x: 200, y: 25 }
  ], style: { color: "#000" } },
  { 
    id: "canvas02",
    type: "curve",
    left: '300px',
    top: '15px',
    data: [
    { x: 20, y: 10 },
    { x: 50, y: 15 },
    { x: 70, y: 5 },
    { x: 90, y: 20 },
    { x: 110, y: 25 }
  ], style: { color: "red" } }
]);

const activeId = ref(null);

const sceneObjs = {};

const width = 1200
const height = 800


const checkActive = (id = null) => {
  if (activeId.value) {
    document.querySelector("#" + activeId.value).classList.remove("active");
  }
  activeId.value = id;
  if (activeId.value) document.querySelector("#" + id).classList.add("active");
}

const initScene = () => {
  list.value.forEach((item, index) => {
    if (!sceneObjs[item.id]) {
      sceneObjs[item.id] = new Scene(item.id, item);
      sceneObjs[item.id].draw();
    }
  });
}

onMounted(() => {
  let senceGridObj = new SenceGrid('canvasGrid', { width, height });
  senceGridObj.draw();

  initScene()
})

const add = () => {
  const len = 5 + Math.floor(Math.random() * 10)
  const grid = 40 + Math.floor(Math.random() * 20)
  const x = 20 + Math.floor(Math.random() * grid)
  const y = 20 + Math.floor(Math.random() * grid)
  const data = [];
  for(let i = 0; i < len; i++) {
    data.push({
      x: x + i * grid,
      y: y + (grid - Math.floor(Math.random() * grid / 2))
    })
  }

  // 生成颜色
  const color = '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')

  const item = {
    type: 'line',
    id: `canvas0${list.value.length + 1}`,
    left: 50 + Math.floor(Math.random() * (width - 300)) + 'px',
    top: 50 + Math.floor(Math.random() * (height - 300)) + 'px',
    data: data,
    style: { color }
  };
  const jsonStr = JSON.stringify(item)
  const newItem = JSON.parse(jsonStr)
  list.value.push(newItem);
  setTimeout(() => {
    sceneObjs[item.id] = new Scene(item.id, newItem);
    sceneObjs[item.id].draw();
  }, 200)
}
</script>

<template>
  <div>
    <h1>
      点击图表 按住进行拖曳
      <button @click="add">添加图表</button>
    </h1>
    <div style="display: flex;justify-content: center;position: relative;">
      <canvas id="canvasGrid" ref="canvas" width="400" height="400" style="margin:50px auto;border:1px solid #999;position: absolute;"></canvas>
      <template v-for="item,key in list" :key="key">
        <canvas 
          :id="item.id" class="view"
          @click="checkActive(item.id)"
         :style="{left: item.left, top: item.top}"></canvas>
      </template>
    </div>
  </div>
</template>
<style scoped>
.view {
  border:1px solid transparent;background: transparent;position: absolute;
}

.view.active {
  border-color: #0b57d0  !important;;
}
</style>